﻿using Cloud.Core.Model.Promotion;
using Cloud.Core.Request.WebChat.PromotionsInsert;
using Cloud.Core.Response;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Cloud.Core.Bizlogic;
using Cloud.Core.Model;
using System.Linq;
using Cloud.Core.Request.WebChat.WxUser;
using Cloud.Core.Response.WxUser;
using Cloud.Core.Response.WebChat.WxUser;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using System;
using Cloud.Core.Services;
using Cloud.Core.Interface;
using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp.WxAppJson;

namespace Cloud.Core.Controllers.WebChat
{
    [Route("api/wx/[controller]")]
    public class NewComerIndexController : Controller
    {
        private readonly CloudDataBase _context;

        IPaymentService _paymentService;

        public NewComerIndexController(CloudDataBase context, IPaymentService paymentService)
        {
            _context = context;
            _paymentService = paymentService;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetNewComerBannerAsync")]
        public async Task<JsonResponse<BannerResponse>> GetNewComerBannerAsync(double latitude, double longitude)
        {

            var listquery = await _context.Banner.Where(t => t.Status == 1).ToListAsync();
            if (listquery.Count > 0)
            {
                var model = listquery.OrderBy(t => MapHelper.GetDistance(t.latitude, t.longitude, latitude, longitude)).First();
                var banner = new BannerResponse()
                {
                    Title = model.Title,
                    Description = model.Description,
                    Image_url = model.Image_url,
                    Link_url = model.Link_url
                };
                model.promotioncountRest -= 1;
                _context.Update(model);
                _= _context.SaveChangesAsync();
                
                return new JsonResponse<BannerResponse>
                {
                    Data = banner,
                    Msg = "获取成功",
                    Status = ResponseStatus.Success
                };
            }
            else 
            {
                return new JsonResponse<BannerResponse>
                {
                    Data = null,
                    Msg = "没有上架的banner",
                    Status = ResponseStatus.ParameterError
                };


            }
        

         
        }
        /// <summary>
        /// 获取新人红包首页列表
        /// </summary>
        /// <param name="promotionsInsertRequest"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetNewComerIndexInfo")]
        public async Task<JsonResponse<NewComerIndexInfoResponse>> GetNewComerIndexInfo(NewComerIndexInfoRquest newComerIndexInfoRquest)
        {
            var banner = await _context.Banner.Where(t => t.Status == 1).
                Select(t => new BannerResponse
                {
                    Title = t.Title,
                    Description = t.Description,
                    Image_url = t.Image_url,
                    Link_url = t.Link_url
                }).FirstOrDefaultAsync();

            var filterQuery = _context.Promotions.Where(o => o.PromotionCount > 0).Select(t => t.PromotionUsersId);

            var PromotionUsers = await _context.PromotionUsers.Where(t => filterQuery.Contains(t.Id) && t.Status == 1)
                .Select(t => new PromotionUsersResponse
                {
                    PromotionGroupId = t.Id,
                    PromotionName = t.PromotionName,
                    PromotionAddress = t.PromotionAddress,
                    PromotionUserType = t.PromotionUserType,
                    SiteInfoImgs = t.SiteInfoImgs,
                    RealNameImgs = t.RealNameImgs,
                    RealNameInfo = t.RealNameInfo,
                    ContactNumber = t.ContactNumber,
                    PromotionImgs = t.PromotionImgs
                })
                .ToListAsync();
            return new JsonResponse<NewComerIndexInfoResponse>
            {
                Data = new NewComerIndexInfoResponse { bannerResponse = banner, promotionUsersResponses = PromotionUsers },
                Msg = "获取成功",
                Status = ResponseStatus.Success
            };


        }
        /// <summary>
        /// 获取新人问题列表
        /// </summary>
        /// <param name="newComerQuestionInfoRequest"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetNewComerQuestionInfo")]
        public async Task<JsonResponse<NewComerQuestionInfoResponse>> GetNewComerQuestionInfo(NewComerQuestionInfoRequest newComerQuestionInfoRequest)
        {
            var PromotionUsers = await _context.PromotionUsers.FindAsync(newComerQuestionInfoRequest.PromotionUsersId);
            var promotions = await _context.Promotions.Where(o => o.PromotionCount > 0 && o.PromotionUsersId == PromotionUsers.Id).FirstOrDefaultAsync();
            if (promotions == null || PromotionUsers == null)
            {
                return new JsonResponse<NewComerQuestionInfoResponse>
                {
                    Msg = "活动已结束",
                    Status = ResponseStatus.ParameterError
                };
            }

            var promotionsNewComerQuestion = await _context.PromotionsNewComerQuestion.Where(t => t.PromotionsId == promotions.Id).FirstOrDefaultAsync();
            var promotionsNewComerAnswer = await _context.PromotionsNewComerAnswer.Where(t => t.NewComerQuestionId == promotionsNewComerQuestion.Id).ToListAsync();

            var PromotionsQuestion = await _context.PromotionsQuestion.FindAsync(promotionsNewComerQuestion.QuestionId);


            return new JsonResponse<NewComerQuestionInfoResponse>
            {


                Msg = "获取成功",
                Status = ResponseStatus.Success,
                Data = new NewComerQuestionInfoResponse
                {
                    PromotionsId = promotions.Id,
                    SiteInfoImgs = PromotionUsers.SiteInfoImgs,
                    promotionsQuestion = PromotionsQuestion,
                    promotionsNewComerAnswer = promotionsNewComerAnswer

                }

            };
        }

        /// <summary>
        /// 提交答案
        /// </summary>
        /// <param name="newComerQuestionInfoRequest"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("SubmitAnswer")]
        public async Task<JsonResponse> SubmitAnswer(SubmitAnswerRequest submitAnswerRequest)
        {
           

            var isExist =await _context.NewComerInterlocution.AnyAsync(t => t.QuestionId == submitAnswerRequest.QuestionId 
            && t.openid == submitAnswerRequest.openid  && t.PromotionsId== submitAnswerRequest.PromotionsId);
            if (isExist)
            {
               
                     return new JsonResponse<bool>
                     {
                         Data = false,
                         Msg = "已参与问答活动",
                         Status = ResponseStatus.Success

                     };
            }
            var isRight = await _context.PromotionsNewComerAnswer.Where(t => t.NewComerQuestionId == submitAnswerRequest.QuestionId && t.Id == submitAnswerRequest.PromotionsNewComerAnswerId && t.IsRight == true).AnyAsync();


            var Interlocution = new NewComerInterlocution
            {

                PromotionsId = submitAnswerRequest.PromotionsId,
                openid = submitAnswerRequest.openid,
                QuestionId = submitAnswerRequest.QuestionId,
                PromotionsNewComerAnswerId = submitAnswerRequest.PromotionsNewComerAnswerId,
                IsrtDt = DateTime.Now,
                isRight = isRight
            };
            await _context.AddAsync(Interlocution);
            await _context.SaveChangesAsync().ConfigureAwait(false);




            if (isRight)
            {
                return new JsonResponse<bool>
                {
                    Data = true,
                    Msg = "回答正确",
                    Status = ResponseStatus.Success

                };
            }
            else
            {
                return new JsonResponse<bool>
                {
                    Data = false,
                    Msg = "谢谢参与",
                    Status = ResponseStatus.Success

                };
            }


            //发送现金红包
            //var result = await _paymentService.Transfers(new PayTransfersRequest()
            //{
            //    PartnerTradeNo = NoGen.Instance.GenOrderNo().ToString(),
            //    OpenId= submitAnswerRequest.openid,
            //    CheckName = submitAnswerRequest.openid,

            //    Amount = 100
            //});



        }
    }
}
